#include "tests/cefclient/browser/urlrequest_client.h"
#include <Windows.h>
#include <conio.h> 

UrlRequestClient::~UrlRequestClient() {
	_cprintf("~UrlRequestClient\n");
}

void UrlRequestClient::OnRequestComplete(CefRefPtr<CefURLRequest> request)
{
	_cprintf("OnRequestComplete    code = %d  status = %d \n", request->GetResponse()->GetError(), request->GetResponse()->GetStatus());
	CEF_REQUIRE_UI_THREAD();
	//_cprintf("OnRequestComplete    code = %d  status = %d \n", request->GetResponse()->GetError(), request->GetResponse()->GetStatus());
	if (m_callback && request->GetResponse()->GetStatus() == 200 && request->GetResponse()->GetError() == 0) {
		m_callback->OnCompletion(request->GetResponse()->GetError(), m_data);
	}
}

void UrlRequestClient::OnUploadProgress(CefRefPtr<CefURLRequest> request, int64 current, int64 total)
{

}

void UrlRequestClient::OnDownloadProgress(CefRefPtr<CefURLRequest> request, int64 current, int64 total)
{
	_cprintf("onDownloadProgress   %d   %d\n", current, total);
	//char szLog[128] = { 0 };
	//sprintf_s(szLog, 128, "UrlRequestClient::OnDownloadProgress, current-%lld, total-%lld\r\n",
	//	current, total);
	//OutputDebugStringA(szLog);
}

void UrlRequestClient::OnDownloadData(CefRefPtr<CefURLRequest> request, const void* data, size_t data_length)
{
	//_cprintf("OnDownloadData    code = %d  status = %d \n", request->GetResponse()->GetError(), request->GetResponse()->GetStatus());
	if (request->GetResponse()->GetStatus() == 200 && request->GetResponse()->GetError() == 0)
	    m_data += std::string(static_cast<const char*>(data), data_length);
	//_cprintf("OnDownloadData %d  [%s]\n", data_length, m_data);
}

void UrlRequestClient::Request(CefRefPtr<CefRequest> cef_request)
{
	m_urlRequest = CefURLRequest::Create(cef_request, this, NULL);
}

void UrlRequestClient::Get(const std::string &url, const CefRequest::HeaderMap &headers /*= CefRequest::HeaderMap()*/)
{
	CefRefPtr<CefRequest> req = CefRequest::Create();
	req->SetURL(url);
	req->SetMethod("GET");
	req->SetHeaderMap(headers);

	Request(req);
}

void UrlRequestClient::Post(const std::string &url, const CefRefPtr<CefPostData> data, const CefRequest::HeaderMap &headers /*= CefRequest::HeaderMap()*/)
{
	CefRefPtr<CefRequest> req = CefRequest::Create();
	req->SetURL(url);
	req->SetMethod("POST");
	req->SetHeaderMap(headers);
	req->SetPostData(data);

	Request(req);
}

//
// for test
//
void PrintUrlReqCallback::OnCompletion(CefURLRequest::ErrorCode errorCode, const std::string& data)
{
	//char szLog[128] = { 0 };
	//sprintf_s(szLog, 128, "PrintUrlReqCallback::OnCompletion, errorCode = %d, data.len = %d, data:\r\n",
	//	errorCode, data.length());
	//OutputDebugStringA(szLog);
	//_cprintf("OnCompletion   [%s]  [%s]\n", szLog, data.c_str());
	delete this;
}